package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolString;
import com.fwtai.web.PartnerAreaDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 合伙|代理的特殊区域业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2023-07-22 14:36:48
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class PartnerAreaService{

  private final PartnerAreaDao partnerAreaDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  private final PartnerService partnerService;

  public PartnerAreaService(final PartnerAreaDao partnerAreaDao,final PartnerService partnerService,final ThreadPoolTaskExecutor taskExecutor){
    this.partnerAreaDao = partnerAreaDao;
    this.partnerService = partnerService;
    this.taskExecutor = taskExecutor;
  }

  public String add(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request);
      final String p_level_value = "level_value";
      final String validate = ToolClient.validateField(formData,p_level_value);
      if(validate != null) return validate;
      final String len_level_value = formData.getString(p_level_value);
      if(len_level_value != null && len_level_value.length() > 1){
        return ToolClient.createJsonFail("等级值（goods_integral.level_value）字数太多");
      }
      final Integer v_level_value = formData.getInteger(p_level_value);
      if(v_level_value == null){
        return ToolClient.createJsonFail("等级值（goods_integral.level_value）不是有效的数字");
      }else{
        formData.put(p_level_value,v_level_value);
      }
      formData.put("area_id",new IdBuilder().getId121L());//todo 视情况是否需要处理主键重复的而需要删除所上传的文件,如以用户主键创建的表,可使用唯一键约束并结合IGNORE使用
      return ToolClient.executeRows(partnerAreaDao.add(formData));
    },taskExecutor).join();
  }

  public String edit(final Long areaId,final Integer level){
    return CompletableFuture.supplyAsync(()->{
      if(areaId == null || level == null){
        return ToolClient.jsonValidateField();
      }
      final HashMap<String,Object> map = new HashMap<>(2);
      map.put("level_value",level);
      map.put("area_id",areaId);
      return ToolClient.executeRows(partnerAreaDao.edit(map));
    },taskExecutor).join();
  }

  public String queryById(final Long area_id){
    return CompletableFuture.supplyAsync(()->{
      if(area_id == null){
        return ToolClient.jsonValidateField();
      }
      return ToolClient.queryJson(partnerAreaDao.queryById(area_id));
    },taskExecutor).join();
  }

  //启禁用
  public String delById(final Long areaId,final Long kid,final Integer disable){
    return CompletableFuture.supplyAsync(()->{
      if(areaId == null || disable == null){
        return ToolClient.jsonValidateField();
      }
      final HashMap<String,Object> map = new HashMap<>(3);
      map.put("deleted",disable);
      map.put("area_id",areaId);
      if(disable == 0){//启用
        if(kid == null){
          return ToolClient.executeRows(partnerAreaDao.editEnable(map),"启用成功","启用失败,刷新重试");
        }else{
          map.put("kid",kid);
          return ToolClient.executeRows(partnerAreaDao.editEnableKid(map),"启用成功","启用失败,刷新重试");
        }
      }else{
        if(kid == null){
          return ToolClient.executeRows(partnerAreaDao.editEnable(map),"启用成功","启用失败,刷新重试");
        }else{
          map.put("kid",kid);
          return ToolClient.executeRows(partnerAreaDao.editPartnerKid(map),"启用成功","启用失败,刷新重试");
        }
      }
    },taskExecutor).join();
  }

  public String delByKeys(final String ids){
    return CompletableFuture.supplyAsync(()->{
      if(ids == null || ids.length() <= 0){
        return ToolClient.jsonValidateField();
      }
      final long[] list = ToolString.keysToArarry(ids);
      if(list == null){
        return ToolClient.createJsonFail("请选择要删除的数据");
      }
      return ToolClient.executeRows(partnerAreaDao.delByKeys(list),"操作成功","数据不存在,刷新重试");
    },taskExecutor).join();
  }

  public String listData(final PageFormData formData){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> partnerAreaDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> partnerAreaDao.getListTotal(formData),taskExecutor);
        return ToolClient.dataTableOK(listData.join(),listTotal.join());
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }

  public String getUserList(final String word){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(word == null || word.length() <= 0){
          return ToolClient.jsonCode198("请输入关键字搜索");
        }
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> partnerAreaDao.getUserList(word),taskExecutor);
        return ToolClient.queryJson(listData.join());
      } catch (final Exception ignored){
        return ToolClient.exceptionJson();
      }
    },taskExecutor).join();
  }

  public String addUser(final HttpServletRequest request,final Integer level){
    return CompletableFuture.supplyAsync(()->{
      if(level == null){
        return ToolClient.jsonValidateField();
      }
      switch (level){
        case 1:
          break;
        case 2:
          break;
        case 3:
          break;
        default:
          return ToolClient.createJsonFail("代理的级别有误");
      }
      final PageFormData formData = new PageFormData(request);
      final String p_area_id = "area_id";
      final String p_user_id = "user_id";
      final String p_province_id = "province_id";
      final String p_province_name = "province_name";
      final String p_city_id = "city_id";
      final String p_city_name = "city_name";
      final String p_county_id = "county_id";
      final String p_county_name = "county_name";
      final String p_real_name = "real_name";
      final String p_id_card = "id_card";
      final String p_phone = "phone";
      final String p_confirm = "confirm";
      final String p_kId = "kId";//为空时说明未绑定
      final Long kid = formData.getLong(p_kId);
      final boolean kId = kid == null;
      if(kId){
        final String validate = ToolClient.validateField(formData,p_area_id,p_user_id,p_province_id,p_province_name,p_city_id,p_city_name,p_county_id,p_county_name,p_real_name,p_id_card,p_phone);
        if(validate != null) return validate;
      }else{
        final String validate = ToolClient.validateField(formData,p_area_id,p_user_id,p_real_name,p_id_card,p_phone);
        if(validate != null) return validate;
      }
      final Long userId = formData.getLong(p_user_id);
      formData.put("roleId",partnerService.getRoleType(level));
      //②查询代理区域是否已有代理
      if(kId){
        //①查询是否是门店|查询是否是代理
        final boolean existProxy = partnerAreaDao.getExistProxy(userId);
        if(existProxy){
          return ToolClient.createJsonFail("绑定的账号已是店主或代理商");
        }
        final HashMap<String,Object> map = new HashMap<>(3);
        map.put("areaId",formData.getLong(p_area_id));//省、市、区、街道
        map.put("userId",userId);
        map.put("level",level);
        final HashMap<String,Object> areaExist = partnerAreaDao.getAreaExist(map);
        if(areaExist != null){
          final Integer confirm = formData.getInteger(p_confirm);
          if(confirm == null){
            return ToolClient.jsonCode198("代理区域已存在代理,是否替换？");
          }else{
            formData.put("keyId",areaExist.get("kid"));
            formData.put("user_id",areaExist.get("user_id"));//用于删除或置空指定角色信息或邀请人
            formData.put("uid",userId);//新的用户id
            formData.put("category",level);//代理类型
            return ToolClient.executeRows(partnerAreaDao.updateProxy(formData),"替换成功","替换失败");//替换代理商
          }
        }
      }
      //③查询特殊区域
      if(kId){
        formData.put("kid",new IdBuilder().getId121L());
        formData.put("address",String.valueOf(formData.get("province_name"))+formData.get("city_name")+formData.get("county_name"));
      }else{
        formData.put("address",getAddress(formData.get("province_name"),formData.get("city_name"),formData.get("county_name")));
      }
      if(kId){
        return ToolClient.executeRows(partnerAreaDao.addProxy(formData),"绑定成功","绑定失败,刷新重试");
      }else{
        final Long _uid = partnerAreaDao.getPartnerUserId(kid);
        if(_uid.equals(userId)){//同一个人,仅修改资料即可
          return ToolClient.executeRows(partnerAreaDao.editProxyInfo(formData),"编辑成功","操作失败,刷新重试");
        }
        formData.put("uid",_uid);
        formData.put("newKid",new IdBuilder().getId121L());
        formData.put("details","换绑,主键"+kid+"已被新的用户id"+userId+"替换");//换绑记录
        return ToolClient.executeRows(partnerAreaDao.editProxy(formData),"编辑成功","操作失败,刷新重试");
      }
    },taskExecutor).join();
  }

  Object getAddress(final Object... address){
    return (address[0] != null ? String.valueOf(address[0]) : "")+(address[1] != null ? String.valueOf(address[1]) : "")+(address[2] != null ? String.valueOf(address[2]) : "");
  }
}